package showtime.framework.utils
{
	import flash.geom.Point;

	/**
	 * @project SunGame
	 * @date 2011-6-12
	 * @author 绿豆蛙
	 * 
	 */
	public final class AlgorithmUtility
	{
		
		/**
		 * Get the angle from 2 point. 
		 * @param fromX
		 * @param fromY
		 * @param toX
		 * @param toY
		 * @return 
		 * 
		 */		
		static public function getAngle(fromX:int, fromY:int, toX:int, toY:int):int
		{
			return (Math.atan2(toY - fromY, toX - fromX) * 180 / Math.PI);
		}
		
		public static function getLineFunc(ponit1:Point, point2:Point, type:int=0):Function
		{
			var resultFuc:Function;
			
			if( ponit1.x == point2.x )
			{
				if( type == 0 )
				{
					throw new Error("两点所确定直线垂直于y轴，不能根据x值得到y值");
				}
				else if( type == 1 )
				{
					resultFuc =	function( y:Number ):Number
					{
						return ponit1.x;
					}
					
				}
				return resultFuc;
			}
			else if( ponit1.y == point2.y )
			{
				if( type == 0 )
				{
					resultFuc =	function( x:Number ):Number
					{
						return ponit1.y;
					}
				}
				else if( type == 1 )
				{
					throw new Error("两点所确定直线垂直于y轴，不能根据x值得到y值");
				}
				return resultFuc;
			}
			
			// 当两点确定直线不垂直于坐标轴时直线方程设为 y = ax + b
			var a:Number;
			
			// 根据
			// y1 = ax1 + b
			// y2 = ax2 + b
			// 上下两式相减消去b, 得到 a = ( y1 - y2 ) / ( x1 - x2 ) 
			a = (ponit1.y - point2.y) / (ponit1.x - point2.x);
			
			var b:Number;
			
			//将a的值代入任一方程式即可得到b
			b = ponit1.y - a * ponit1.x;
			
			//把a,b值代入即可得到结果函数
			if( type == 0 )
			{
				resultFuc =	function( x:Number ):Number
				{
					return a * x + b;
				}
			}
			else if( type == 1 )
			{
				resultFuc =	function( y:Number ):Number
				{
					return (y - b) / a;
				}
			}
			
			return resultFuc;
		}
		
		/**
		 * 得到两点间连线的斜率 
		 * @param ponit1	
		 * @param point2
		 * @return 			两点间连线的斜率 
		 * 
		 */		
		static public function getSlope( ponit1:Point, point2:Point ):Number
		{
			return (point2.y - ponit1.y) / (point2.x - ponit1.x); 
		}

	}
}